<template>
  <view class="search-details-page">
    <!-- 搜索导航栏 -->
    <nav-bar @load="handleNavLoad">
      <uni-easyinput prefixIcon="search" v-model="searchContent" :inputBorder="false" @input="handleGetSearchSuggest"
        placeholder="请输入搜索内容" @confirm="handleSearch(searchContent)" @clear="handlePageInit">
      </uni-easyinput>
    </nav-bar>

    <!-- 搜索建议列表 -->
    <view class="sugg-list-container" v-if="searchSuggeListShow" :style="{height:suggHeight+'px',top:navHeight+'px'}">
      <view class="sugg-item" v-for="(item,index) in SearchSuggeList" :key="index" @click="handleSearch(item)">
        <uni-icons type="search" :size="16" color="#ccc"></uni-icons>
        <view class="sugg-item-text">
          <text>{{item}}</text>
        </view>
      </view>
      <view class="sugg-tips">
        已经全部加载
      </view>
    </view>

    <!-- 搜索历史区域 -->
    <view class="history-container" v-if="historyList.length>0">
      <!-- 标题 -->
      <view class="history-title">
        <text class="title">搜索历史</text>
        <view class="history-compile" v-if="historyEditStatus">
          <text class="history-empty" @click="handleCleanHistory">清空</text>
          <text>|</text>
          <text class="history-cancel" @click="historyCancel">取消</text>
        </view>
        <uni-icons v-else custom-prefix="iconfont" type="icon-delete" :size="16" @click="historyCancel">
        </uni-icons>
      </view>
      <!-- 列表 -->
      <view class="history-list-container">
        <view class="history-item" @longpress='handleRemoveSingleHistory(item)' v-for="(item, index) in historyList"
          :key="index" @click="handleHistoryClick(item)">
          <user-select class="text">{{item}}</user-select>
          <uni-icons class="remove-icon" custom-prefix="iconfont" type="icon-delete" :size="12"
            v-if="historyEditStatus">
          </uni-icons>
        </view>
        <view class="history-item more-icon" :class="{'more-icon-expland':showAllHistoryListState}"
          v-if="historyListMoreStatus" @click="handleLoadMoreHistory">
          <uni-icons class="icon" type="bottom" :size="16"></uni-icons>
        </view>
      </view>
    </view>

    <!-- 内容区域 -->
    <view class="content-container">
      <!-- 选项卡 -->
      <view class="nav-container">
        <tabs-component :data="navList" :active="active" @change="handleNavChange"></tabs-component>
      </view>
      <view class="scroll-view-container" :style="{'height':contentHeight+'px'}">

        <!-- 文章 与 文章列表 -->
        <scroll-view scroll-y :show-scrollbar="false" class="recommend-container" v-show="active === 0"
          @scrolltolower="handleLowerBottom">
          <view class="list-container">

            <!-- 搜索列表 -->
            <view v-for="item in ArticleListPage.list" :key='item.intactArticleId' class="item">
              <article-block :data="item"></article-block>
            </view>

            <view class="list-status-container" v-if="searchContent&&ArticleListPage.status!='loadmore'">
              <text v-if="ArticleListPage.status=='loading'">加载中...</text>
              <text v-else-if="ArticleListPage.status=='nomore'&&ArticleListPage.list.lengt>0">已全部加载</text>
              <text v-else-if="ArticleListPage.status=='nomore'&&ArticleListPage.list.length==0">没有找到你要搜索的内容...</text>
            </view>

            <!-- 推荐列表-->
            <view class="recommend-article" v-if="searchContent&&ArticleListPage.list.length==0||!searchContent">
              <view class="item" v-for="(item,index) in ArticleListPage.recommendList" :key='item.id'
                @click="handleNavigateToArticleDetails(item)">
                <view class="frame-item">{{index+1}}</view>
                <view class="text-item">
                  <text>{{item.title}}</text>
                </view>
              </view>
            </view>

          </view>
        </scroll-view>

        <!-- 用户列表 -->
        <scroll-view scroll-y :show-scrollbar="false" class="user-container" v-show="active === 1"
          @scrolltolower="handleLowerBottom">
          <view class="list-container">
            <!-- 搜索后的用户列表 -->
            <view v-for="item in userListPage.list" :key='item.userId' class="item"
              :class="{'item-one':userListPage.list.length==1}">
              <user-item :userObj="item" @status-change="changeUserFansStateHandle" :all="0" :userType='3'>
              </user-item>
            </view>

            <view class="list-status-container" v-if="searchContent&&userListPage.status!='loadmore'">
              <text v-if="userListPage.status=='loading'">加载中...</text>
              <text v-else-if="userListPage.status=='nomore'&&userListPage.list.lengt>0">已全部加载</text>
              <text v-else-if="userListPage.status=='nomore'&&userListPage.list.length==0">没有找到你要搜索的内容...</text>
            </view>

            <!-- 热门用户 -->
            <view class='recommend-user' v-if="searchContent&&userListPage.list.length==0||!searchContent">
              <view v-for="item in userListPage.recommendList" :key='item.userId' class="item">
                <user-item :userObj="item" @status-change="handleUserFansState" :all="0" :userType="2">
                </user-item>
              </view>
            </view>
          </view>
        </scroll-view>

      </view>

    </view>


  </view>
</template>
<script>
  // 因模拟数据量较大 所以将模拟数据全部放入了一个json文件中
  import {
    HotArticles, // 热门文章
    Articles, // 文章
    HotUsers, // 热门用户
    Users, // 用户列表
    SearchSuggeList // 搜索建议列表
  } from "./data.json"
  // 历史记录列表默认显示个数
  const HISTORY_LIST_SHOW_NUM = 4;
  
  export default {
    data() {
      return {
        windowHeight: 0,
        navHeight: 0, // 导航栏高度
        suggHeight: 0, // 搜索建议高度
        contentHeight: 0, // 可滚动区域内容高度
        searchContent: '', // 搜素内容
        // 文章列表数据
        ArticleListPage: {
          status: 'loadmore',
          pageNum: 1,
          totalPageNum: 0,
          pagesize: 0,
          total: 0,
          recommendList: [], // 推荐列表
          list: [], // 搜索结果列表
        },
        // 用户列表数据
        userListPage: {
          status: 'loadmore',
          pageNum: 1,
          totalPageNum: 0,
          pagesize: 0,
          total: 0,
          recommendList: [],
          list: []
        },
        historyEditStatus: false, //搜索历史编辑状态
        sourceHistoryList: [], // 历史搜索记录 原数据
        showAllHistoryListState: false,
        searchSuggeListShow: false, //搜索建议列表显示状态
        SearchSuggeList: [], // 搜索结果列表
        active: 0, // 选项卡激活索引
        // 选项卡列表数据
        navList: [{
            text: "文章",
          },
          {
            text: "用户",
          }
        ],
      };
    },
    onShow() {
      this.handleInit();
    },
    methods: {
      // 初始化
      handleInit() {
        this.handleContentHeight();
        this.handleGetHistoryList()
        this.handleGetHotDisclos()
        this.handleGetHotUse()
      },
      //  导航栏load事件
      handleNavLoad({
        height,
        navHeight
      }) {
        this.windowHeight = height;
        // 获取导航栏高度
        this.navHeight = navHeight;
        // 建议列表区域高度
        this.suggHeight = height - navHeight;
      },
      // 获取热门文章推荐
      handleGetHotDisclos() {
        this.ArticleListPage.recommendList = HotArticles
      },
      // 获取热门用户推荐
      handleGetHotUse() {
        this.userListPage.recommendList = HotUsers
      },
      // 跳转到文章详情页
      handleNavigateToArticleDetails(item) {
        uni.navigateTo({
          url: `/pages/community/article-details/article-details?id=${item.id}`,
        });
      },
      // 计算滚动区域的高度
      handleContentHeight() {
        // 因小程序平台兼容原因 采用节点方式获取指定元素信息  https://uniapp.dcloud.net.cn/api/ui/nodes-info.html#createselectorquery
        const query = uni.createSelectorQuery().in(this);
        query.select('.nav-container').boundingClientRect(data => {
          // 滚动区域的高度等于屏幕高度 - 导航栏高度 - 选项卡高度。
          this.contentHeight = this.windowHeight - this.navHeight - data.height;
        }).exec();
      },
      // ------------------------------------------------------------------------------- 历史记录
      // 删除历史记录
      handleRemoveHistory() {
        let arr = JSON.parse(uni.getStorageSync('kw'))
        if (arr.length <= 0) {
          uni.showModal({
            content: '暂无搜索历史',
          })
          return
        }
        this.historyEditStatus = !this.historyEditStatus
      },

      // 更多历史记录
      handleLoadMoreHistory() {
        this.showAllHistoryListState = !this.showAllHistoryListState;
      },
      // 点击取消恢复默认
      historyCancel() {
        this.historyEditStatus = !this.historyEditStatus
      },
      //点击删除历史或进行搜索
      handleHistoryClick(item) {
        if (this.historyEditStatus) {
          // 编辑状态下 点击标签 删除历史记录
          this.handleRemoveSingleHistory(item)
        } else {
          // 重置分页数据
          this.handlePageInit();
          // 非编辑状态下 点击历史记录 开始搜索
          this.handleSearch(item)
        }
      },
      // 保存搜索关键词的方法
      handleSaveSearchHistory(name) {
        // 利用set数据结构特性 元素不重复 https://es6.ruanyifeng.com/#docs/set-map
        const set = new Set(this.sourceHistoryList)
        // 先删除在添加 避免重复元素
        set.delete(name)
        set.add(name)
        this.sourceHistoryList = Array.from(set)
        uni.setStorageSync('kw', JSON.stringify(this.sourceHistoryList))
      },
      // 清空历史记录
      handleCleanHistory() {
        uni.showModal({
          title: '提示',
          content: '是否清空历史记录',
          success: (res) => {
            if (res.confirm) {
              this.sourceHistoryList = []
              uni.setStorageSync('kw', '[]')
              this.historyEditStatus = false
            }
          }
        });

      },
      // 删除单个历史搜索记录
      handleRemoveSingleHistory(name) {
        uni.showModal({
          title: '提示',
          content: '是否清除当前历史记录',
          success: (res) => {
            if (res.confirm) {
              const set = new Set(this.sourceHistoryList)
              set.delete(name)
              this.sourceHistoryList = Array.from(set)
              uni.setStorageSync('kw', JSON.stringify(this.sourceHistoryList))
            }
          }
        });

      },
      // 处理历史搜索记录
      handleGetHistoryList() {
        this.sourceHistoryList = JSON.parse(uni.getStorageSync('kw') || '[]');
      },
      // ------------------------------------------------------------------------------------
      // 热门用户互关状态改变事件
      changeUserFansStateHandle({
        id,
        fansState
      }) {
        const item = this.userListPage.list.find(item => item.userId == id)
        item.fansState = !fansState
        if (item.mutualConcern) {
          item.mutualConcern = false
        } else {
          item.mutualConcern = true
        }
      },
      // 用设置用户关注状态
      handleUserFansState({
        id,
        fansState
      }) {
        const item = this.userListPage.recommendList.find(item => item.userId == id)
        item.fansState = !fansState
        if (item.mutualConcern) {
          item.mutualConcern = false
        } else {
          item.mutualConcern = true
        }
      },
      // 获取搜索建议
      handleGetSearchSuggest(value) {
        if (!value.trim()) {
          // 搜索内容为空时 恢复默认状态
          this.handlePageInit()
          return;
        }
        // 防抖
        clearTimeout(this.time)
        this.time = setTimeout(() => {
          this.active = 0;
          // 获取搜索建议列表
          let arr = SearchSuggeList.filter((item) => {
            return item.indexOf(value.trim()) > -1;
          })
          if (arr.length > 0) {
            this.SearchSuggeList = arr;
            this.searchSuggeListShow = true;
          } else {
            this.searchSuggeListShow = false;
          }
        }, 300)

      },
      // 分页初始化
      handlePageInit() {
        this.ArticleListPage.pageNum = 1;
        this.userListPage.pageNum = 1;

        this.ArticleListPage.list = [];
        this.userListPage.list = [];

        this.ArticleListPage.status = 'loadmore';
        this.userListPage.status = 'loadmore';

        this.ArticleListPage.totalPageNum = 0;
        this.userListPage.totalPageNum = 0;

        this.searchSuggeListShow = false
        this.historyEditStatus = false
        this.handleGetHistoryList()
      },
      // 用户进行搜索（回车搜索 搜索建议列表点击）
      handleSearch(searchContent) {
        // 关闭显示建议列表
        this.searchSuggeListShow = false;
        if (searchContent.trim() === '') {
          this.handlePageInit();
          return
        }
        // 设置搜索内容
        this.searchContent = searchContent.trim();
        if (this.active === 0) {
          this.ArticleListPage.list = Articles;
          this.ArticleListPage.status = 'nomore';
        } else {
          this.userListPage.list = Users;
          this.ArticleListPage.status = 'nomore';
        }
        this.handleSaveSearchHistory(this.searchContent)
      },
      // 下可滚动区域拉触底
      handleLowerBottom() {
        this.handleSearch(this.searchContent)
      },
      // 选项卡切换
      handleNavChange(index) {
        this.active = index;
        this.handlePageInit();
        this.handleSearch(this.searchContent)
      }
    },
    computed: {
      // 历史记录列表
      historyList() {
        if (this.showAllHistoryListState) {
          return this.sourceHistoryList;
        } else {
          return this.sourceHistoryList.slice(0, HISTORY_LIST_SHOW_NUM);
        }
      },
      // 是否显示显示更多 - 历史记录元素是否超出HISTORY_LIST_SHOW_NUM定义
      historyListMoreStatus() {
        return this.sourceHistoryList.length > HISTORY_LIST_SHOW_NUM;
      },
    }
  }
</script>
<style lang="scss" scoped>
  .search-details-page {
    width: 100%;
    height: 100vh;
    overflow-y: auto;
    background-color: #eef2f4;

    // 搜索建议区域
    .sugg-list-container {
      background: #fff;
      position: fixed;
      left: 0;
      top: 0;
      width: 100%;
      box-shadow: 0px 2px 4px 0px rgba(0, 0, 0, 0.1);
      border-radius: 32rpx;
      z-index: 1;

      .sugg-item {
        font-size: 24rpx;
        padding: 26rpx;
        display: flex;
        align-items: center;
        border-bottom: 2rpx solid #EEF2F4;
        box-sizing: border-box;

        .sugg-item-text {
          margin-left: 28rpx;
          // 文字不允许换行（单行文本）
          white-space: nowrap;
          // 溢出部分隐藏
          overflow: hidden;
          // 文本溢出后，使用 ... 代替
          text-overflow: ellipsis;
          margin-right: 6rpx;
        }
      }

      .sugg-tips {
        width: 100%;
        text-align: center;
        padding: 40rpx 0rpx;
        color: #AEAEAE;
        font-size: 24rpx;
        border-top: solid #EEF2F4 1px;
      }
    }

    // 搜索历史区域
    .history-container {
      width: 100%;
      padding: 36rpx 32rpx;
      box-sizing: border-box;

      .history-title {
        display: flex;
        justify-content: space-between;
        align-items: center;
        height: 40rpx;

        .title {
          font-size: 28rpx;
        }

        .history-compile {
          font-size: 24rpx;
          display: flex;
          align-items: center;
          justify-content: center;

          .history-empty {
            margin-right: 4rpx;
            color: #3FD3D1;
          }

          .history-cancel {
            margin-left: 4rpx;
          }
        }
      }

      .history-list-container {
        display: flex;
        flex-wrap: wrap;

        .history-item {
          min-width: 75rpx;
          max-width: 200rpx;
          height: 48rpx;
          line-height: 48rpx;
          text-align: center;
          border-radius: 30rpx;
          padding: 0 32rpx;
          background: #F5F5F5;
          position: relative;
          margin-top: 32rpx;
          margin-right: 16rpx;

          .text {
            font-size: 26rpx;
            color: #7A7A7A;
            display: -webkit-box;
            text-overflow: ellipsis;
            overflow: hidden;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 1;
          }

          .remove-icon {
            position: absolute;
            top: 0;
            right: 0;
            transform: translateX(50%) translateY(-50%);
          }
        }

        .more-icon .icon {
          display: inline-block;
          transition: all 0.3s ease;
          transform: rotateZ(0deg);
        }

        .more-icon-expland .icon {
          transform: rotateZ(180deg);
        }

      }
    }

    .content-container {

      // 搜素tabs
      .nav-container {
        width: 400rpx;
        box-sizing: border-box;
      }

      .scroll-view-container {
        width: 100%;

        .recommend-container {
          padding: 0rpx 32rpx;
          box-sizing: border-box;
          width: 100%;
          height: 100%;

          .list-container {
            padding-top: 32rpx;
            box-sizing: border-box;



            .recommend-article {
              width: 100%;
              border-radius: 16px;
              background: url('@/static/bluebakcground.png') no-repeat;
              background-size: 100% 100%;
              display: flex;
              flex-direction: column;
              align-items: flex-end;
              padding: 48rpx 32rpx;
              box-sizing: border-box;



              .item {
                width: 100%;
                display: flex;
                align-items: center;
                position: relative;
                margin-bottom: 48rpx;

                .frame-item {
                  width: 32rpx;
                  height: 32rpx;
                  background: #cccccc;
                  color: #fff;
                  border-radius: 10rpx;
                  display: flex;
                  align-items: center;
                  justify-content: center;
                  flex-shrink: 0;
                  font-size: 24rpx;
                }

                .text-item {
                  height: 100%;
                  font-size: 28rpx;
                  font-weight: 500;
                  letter-spacing: 1px;
                  color: #333333;
                  white-space: nowrap;
                  text-overflow: ellipsis;
                  overflow: hidden;
                  -webkit-box-orient: vertical;
                  -webkit-line-clamp: 1;
                  padding-left: 10rpx;
                }
              }

              .item:last-child {
                margin-bottom: 0rpx;
              }

              .item:first-child .frame-item {
                background: #EB4C39 !important;
              }

              .item:nth-child(2) .frame-item {
                background: #EE8041 !important;
              }

              .item:nth-child(3) .frame-item {
                background: #F2A748 !important;
              }

            }

          }

        }


        // 用户
        .user-container {
          padding: 0rpx 32rpx;
          box-sizing: border-box;
          width: 100%;
          height: 100%;

          .list-container {
            padding: 32rpx 0;
            box-sizing: border-box;

            .item {
              background: #ffffff;
              width: 100%;
              padding: 32rpx;
              box-sizing: border-box;
              position: relative;

              // 底部边框
              &::after {
                position: absolute;
                width: calc(100% - 64rpx);
                left: 32rpx;
                bottom: 0rpx;
                height: 1px;
                background: #EEF2F4;
                content: "";
              }
            }

            .item:first-child {
              border-radius: 20px 20px 0px 0px;
            }

            .item:last-child {
              border-radius: 0px 0px 20px 20px;

              &::after {
                display: none;
              }
            }

            .item-one {
              border-radius: 20px !important;
            }

            .recommend-user {
              background: white;
              border-radius: 20px;
            }
          }

        }

      }

      .list-status-container {
        width: 100%;
        text-align: center;
        padding: 40rpx 0rpx;
        color: #AEAEAE;
        font-size: 24rpx;
        border-top: solid #EEF2F4 1px;
      }

    }

  }
</style>